<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="false"
    :visible="visible"
    @close="onClose"
    :destroyOnClose="true"
    :width="950"
    :headerStyle="{ position: 'fixed', top: 0, width: '100%', background: '#fff', zIndex: 2 }"
    :body-style="{ paddingBottom: '80px' }"
  >
    <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 15 }, sm: { span: 17 } }" style="padding-top: 60px">
      <a-form-item label="标题">
        <a-input v-decorator="['title', { rules: [{ required: true, message: '请输入标题！', whitespace: true, max: 36 }] }]" :max-length="36" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-form-item label="关键字">
        <a-input v-decorator="['keys', { rules: [{ required: true, message: '请输入关键字！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
        <div>多个关键词，请用英文,隔开</div>
      </a-form-item>
      <a-form-item label="送券类型" required>
        <a-select v-decorator="['expireType', { initialValue: 0 }]" placeholder="请选择" @change="e => handleSelectChange(e)">
          <a-select-option :value="0">直接到账</a-select-option>
          <a-select-option :value="1">红包领取</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="关联优惠券" v-if="type == 0" required>
        <a-button type="primary" @click="openCoupons"><a-icon type="plus" />添加</a-button>
        <span class="tip" v-show="vouchersTip" style="margin-left:12px">请选择优惠券</span>
        <!-- <a-tooltip>
          <template slot="title" v-if="vouchersList && vouchersList.length > 2">
            {{ vouchersName(vouchersList, brandsList) }}
          </template>
          <a-select
            mode="multiple"
            :maxTagCount="2"
            autoClearSearchValue
            allowClear
            v-decorator="['type', { rules: [{ required: true, message: '请选择！' }] }]"
            placeholder="请选择"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
            show-search
            :filter-option="filterOption"
            @change="changeVouchers"
          >
            <a-select-option v-for="(item, index) in brandsList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-tooltip> -->
      </a-form-item>
      <div style="margin-bottom:24px" v-if="type == 0"><CouponTable ref="vouchersTable" @updateCoupons="updateCoupons"></CouponTable></div>
      <a-form-item label="关联红包活动" v-if="type == 1">
        <a-select
          v-decorator="['redType', { rules: [{ required: true, message: '请选择！' }] }]"
          placeholder="请选择"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
          show-search
          :filter-option="filterOption"
        >
          <a-select-option v-for="(item, index) in brandsRedList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="券数量" v-if="type == 0">
        <a-input
          v-decorator="['voucherNumber', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入有效值，且是正整数！', whitespace: true }] }]"
          name="name"
          placeholder="请输入"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="小程序卡片标题" v-if="type == 0">
        <a-input v-decorator="['cardTitle', { rules: [{ required: true, message: '请输入小程序卡片标题！', max: 36 }] }]" :max-length="36" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-form-item label="小程序卡片缩略图" required v-if="type == 0">
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="fileChange" v-model="cardImg"></JImageUpload>
        <div class="tip" v-show="tips.cardImg">请上传图片！</div>
      </a-form-item>
      <a-form-item label="开启状态">
        <a-switch v-decorator="['status', { rules: [{ required: true }], initialValue: true, valuePropName: 'checked' }]" checked-children="开" un-checked-children="关" />
      </a-form-item>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">取消</a-button>
        <a-button type="primary" htmlType="submit">确定</a-button>
      </div>
    </a-form>
    <CouponModal ref="couponModal" @handleAddCoupons="handleAddCoupons"></CouponModal>
  </a-drawer>
</template>
<script>
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import pick from 'lodash.pick'
import CouponTable from '@/views/box/components/couponModal/couponTable'
import { CouponModal } from '@/views/box/components'
import { couponList, activityList, replyCreate, replyDetail } from '@/api/box/setting'
export default {
  props: ['uploadParams'],
  components: { JImageUpload, CouponTable, CouponModal },
  data() {
    return {
      couponTitle: '关联优惠券',
      visible: false,
      isStatus: false,
      replyId: '',
      coupon: {},
      title: '',
      brandsList: [],
      brandsRedList: [],
      seasonList: [],
      smallList: [],
      bigList: [],
      type: 0,
      form: this.$form.createForm(this),
      toggle: {
        expireType: 0
      },
      imgObj: {
        cardImg: []
      },
      tips: {
        cardImg: false
      },
      cardImg: [],
      vouchersList: [],
      vouchersTip: false
    }
  },

  computed: {
    vouchersName(list, coupons) {
      return (list, coupons) => {
        let arr = coupons.filter(e => list.includes(e.id))
        return arr.map(i => i.name).join(',')
      }
    }
  },
  mounted() {
    this.couponData()
    this.envelopeData()
  },
  methods: {
    // 优惠卷数据
    couponData() {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 100
        },
        requestData: {}
      }
      couponList(params).then(res => {
        if (res.code == 0) {
          this.brandsList = res.data
        }
      })
    },
    // 回显券
    fetchCouponList(list) {
      let params = {
        page: {
          pageSize: 100,
          pageNo: 1
        },
        requestData: {
          ruleIds: list
        }
      }
      return couponList(params).then(res => {
        if (res.code == 0) {
          this.vouchersList = res.data
          this.$refs.vouchersTable.setData(this.vouchersList)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    /**
     * 选择优惠券
     */
    openCoupons() {
      this.$refs.couponModal.show()
    },
    handleAddCoupons(list) {
      let coupons = [...this.vouchersList, ...list]
      let newArr = coupons.filter((currentValue, currentIndex, sourceArr) => {
        return sourceArr.findIndex(x => x.id === currentValue.id) === currentIndex
      })
      this.vouchersList = newArr
      this.$refs.vouchersTable.setData(this.vouchersList)
    },
    updateCoupons(list) {
      this.vouchersList = list
    },
    // 红包活动数据
    envelopeData() {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 1000
        },
        requestData: {
          status: 1 // 上架红包
        }
      }
      activityList(params).then(res => {
        if (res.code == 0) {
          this.brandsRedList = res.data
        }
      })
    },
    handleSelectChange(value) {
      this.type = value
      if (value == 0) {
        this.couponData()
      } else {
        this.envelopeData()
      }
    },
    // 上传图片
    fileChange(list) {
      this.imgObj.cardImg = list
      this.tips.cardImg = false
    },

    onClose() {
      this.tips.cardImg = false
      this.cardImg = []
      this.form.resetFields()
      this.visible = false
    },
    // 弹框
    showModal(id) {
      this.replyId = id
      if (this.replyId != 'add') {
        this.replyDetail()
        this.title = '编辑'
      } else {
        this.title = '新增'
      }
      this.visible = true
    },
    // 下拉框搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    changeVouchers(value) {
      console.log(value)
      this.vouchersList = value
    },
    // 保存
    handleSubmit(e) {
      e.preventDefault()
      if (this.imgObj.cardImg && this.imgObj.cardImg.length > 0) {
        this.tips.cardImg = false
      } else {
        this.tips.cardImg = true
      }
      if (this.type == 0 && this.vouchersList.length == 0) {
        this.vouchersTip = true
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.vouchersTip = false
          let formValue = ''
          if (values.redType) {
            formValue = JSON.parse(JSON.stringify(values))
            formValue.imgUrl = ''
            formValue.voucherId = ''
            formValue.activityId = formValue.redType
            formValue.status = formValue.status ? 1 : 0
            delete formValue.expireType
          } else {
            formValue = JSON.parse(JSON.stringify(values))
            formValue.imgUrl = this.imgObj.cardImg[0].url
            formValue.voucherId = this.type == 0 ? this.vouchersList.map(e => e.id).join(',') : ''
            formValue.activityId = formValue.expireType == 1 && formValue.redType ? formValue.redType : ''
            formValue.status = formValue.status ? 1 : 0
            delete formValue.expireType
            delete formValue.type
          }

          this.submitForm(formValue)
        }
      })
    },
    submitForm(value) {
      let params = {
        requestData: value
      }
      if (this.replyId != 'add') params.requestData.id = this.replyId
      replyCreate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          this.onClose()
          this.$emit('editOk')
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 回显
    replyDetail() {
      let self = this
      let params = {
        requestData: {
          id: this.replyId
        }
      }
      replyDetail(params).then(res => {
        if (res.code == 0) {
          let data = res.data
          data.type = data.voucherId ? data.voucherId.split(',') : ''
          let list = data.voucherId ? data.voucherId.split(',') : []
          if (list.length > 0) this.fetchCouponList(list)

          data.redType = data.activityId ? data.activityId : ''
          data.expireType = data.voucherId ? 0 : 1
          data.status = data.status == 1 ? true : false
          this.type = data.voucherId ? 0 : 1
          this.cardImg = data.imgUrl ? [data.imgUrl] : ''
          this.$nextTick(() => {
            if (data.voucherId) {
              self.form.setFieldsValue(pick(data, 'title', 'keys', 'voucherNumber', 'cardTitle', 'status', 'expireType'))
            } else {
              self.form.setFieldsValue(pick(data, 'title', 'keys', 'status', 'redType', 'expireType'))
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: -8px;
}
</style>

